package small.common.executeEngine.engine.execute;

import small.common.core.exceptions.CommonException;
import small.common.core.thread.util.ThreadUtil;
import small.common.executeEngine.engine.AbstractTaskExecuteEngine;
import small.common.executeEngine.processor.TaskExecuteWorker;
import small.common.executeEngine.processor.TaskProcessor;
import small.common.executeEngine.task.AbstractExecuteTask;
import small.common.log.LogProvider;
import org.slf4j.Logger;

import java.util.Collection;

public class ExecuteTaskExecuteEngine extends AbstractTaskExecuteEngine<AbstractExecuteTask> {

    private final TaskExecuteWorker[] executeWorkers;

    public ExecuteTaskExecuteEngine(String name) {
        this(name, LogProvider.getLogger(ExecuteTaskExecuteEngine.class), ThreadUtil.getSuitableThreadCount(1));
    }

    public ExecuteTaskExecuteEngine(String name, Logger logger) {
        this(name, logger, ThreadUtil.getSuitableThreadCount(1));
    }

    public ExecuteTaskExecuteEngine(String name, Logger logger, int dispatchWorkerCount) {
        super(logger);
        executeWorkers = new TaskExecuteWorker[dispatchWorkerCount];
        for (int mod = 0; mod < dispatchWorkerCount; ++mod) {
            executeWorkers[mod] = new TaskExecuteWorker(name, mod, dispatchWorkerCount, this.log);
        }
    }

    @Override
    public void addTask(Object key, AbstractExecuteTask task) {
        TaskProcessor processor = getProcessor(key);
        if (null != processor) {
            processor.process(task);
            return;
        }
        TaskExecuteWorker worker = getWorker(key);
        worker.process(task);
    }

    @Override
    public AbstractExecuteTask removeTask(Object key) {
        log.warn("ExecuteTaskEngine do not support remove task");
        return null;
    }

    @Override
    public Collection<Object> getAllTaskKeys() {
        log.warn("ExecuteTaskEngine do not support get all task keys");
        return null;
    }

    @Override
    public void shutdown() throws CommonException {
        for (TaskExecuteWorker each : executeWorkers) {
            each.shutdown();
        }
    }

    /**
     * 获取工作线程的状态
     *
     * @return
     */
    public String workersStatus() {
        StringBuilder sb = new StringBuilder();
        for (TaskExecuteWorker worker : executeWorkers) {
            sb.append(worker.status()).append("\n");
        }
        return sb.toString();
    }

    private TaskExecuteWorker getWorker(Object tag) {
        int idx = (tag.hashCode() & Integer.MAX_VALUE) % workersCount();
        return executeWorkers[idx];
    }

    private int workersCount() {
        return executeWorkers.length;
    }


}
